﻿using Client.CBMDataSelection;
using Client.HttpHelp;
using Client.ICommandNotify;
using Client.Models;
using Client.WorkLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Client.ViewModel.ProjcetViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class RoutineViewModel: NotifyBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public RoutineViewModel()
        {
            Selectcommand = new Command(ReverseDoExecute, ReverseCanExecute);
            AddModularListCommand = new Command(AddModularListCommandMethodDoExecute, AddModularListCommandMethodCanExecute);
            Folwcommand = new Command(FolwcommandDoExecute, FolwcommandCanExecute);
            //FolwModularListCommand = new Command(FolwModularListCommandDoExecute, FolwModularListCommandCanExecute);
        }



        #region 方法
        /// <summary>
        /// 查询审核历史
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void FolwcommandDoExecute(object obj)
        {
            TaskList= await  Task.Run(() =>
            {
                var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
                DbContext_.SqlConfigstr = $"Data Source=192.168.100.6;Initial Catalog={SelectModular};User ID=sa;Password=asdw@122";
                var data = DbContext_.Where($"SELECT * FROM [dbo].[{SelectType}] WHERE BillNo='{WORKIDNumber}'");
                if (data.Rows.Count > 0 && string.IsNullOrWhiteSpace(data.Rows[0]["WorkId"].ToString()) == false)
                {
                    // int iWorkId = -1;
                    try
                    {
                        //iWorkId = Convert.ToInt32(data.Rows[0]["WorkId"].ToString());
                    }
                    catch (FormatException)
                    {

                    }
                    DbContext_.SqlConfigstr = "Data Source=192.168.100.150;Initial Catalog=SRBG_FlowEngin;User ID=sa;Password=sclq@pcwp1.0";//切换为流程引擎数据库

                    var da1 = DbContext_.Where($"SELECT STATE from WORK WHERE WORKID = '{data.Rows[0]["WorkId"]}'").Select().Select(o =>
                    {
                        return new
                        {
                            fieid =int.Parse(o["STATE"]?.ToString())
                        };
                    });
                    if(!(da1.Any()&&(da1.FirstOrDefault()?.fieid==0|| da1.FirstOrDefault()?.fieid == 1)))
                    {
                        WPFDevelopers.Minimal.Controls.MessageBox.Show("流程状态异常请手动处理在查询", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                        return new List<TaskLsit>();
                    }
                    var da = DbContext_.Where($"SELECT ISNULL(IsBack,0) as fieid  FROM dbo.WORK WITH (NOLOCK)  WHERE WORKID='{data.Rows[0]["WorkId"]}'").Select().Select(o =>
                    {
                        return new
                        {
                            fieid = o["fieid"].ToString()
                        };
                    });
                    if (da == null ? false : Convert.ToInt32(da.First().fieid) == 1)
                    {
                        return DbContext_.Where<TaskLsit>($"SELECT UnitName, UserName AS AssignUser,UserTitle,NotifyTime,CompleteTime,Opinion FROM dbo.TaskHistory WITH (NOLOCK)  WHERE WORKID='{data.Rows[0]["WorkId"]}' ORDER BY NotifyTime");
                    }
                    else
                    {
                        var dtltask = DbContext_.Where<TaskLsit>($"SELECT C.UNITNAME as UnitName, A.USERNAME as AssignUser,A.RoleName as UserTitle,A.OPINION as Opinion, B.NOTIFYTIME as NotifyTime, A.FINISHTIME as CompleteTime " +
                            $" FROM USERDISP A WITH(NOLOCK) INNER JOIN TASK B WITH(NOLOCK) ON A.TASKID = B.TASKID  " +
                            $" INNER JOIN UNIT C WITH(NOLOCK) ON B.UNITID = C.UNITID  " +
                            $" INNER JOIN WORK D WITH(NOLOCK) ON B.WORKID = D.WORKID " +
                            $" LEFT JOIN TASKORDER E ON B.TASKID = E.NEXTTASKID  " +
                            $" WHERE D.STATE <> 2 AND  " +
                            $" D.WORKID = '{data.Rows[0]["WorkId"]}'  " +
                            $" ORDER BY E.PRIORTASKID");
                        DbContext_.SqlConfigstr = "Data Source=192.168.100.25;Initial Catalog=SRBG_Basic;User ID=pcwp;Password=pcwpasdw@123;";
                        var username = DbContext_.Where($"SELECT a.UserId,a.UserName FROM Sys_User a WHERE UserId in ({string.Join(",", dtltask.Select(o => $"'{o.AssignUser}'"))})").Select().Select(t =>
                        {
                            return new
                            {
                                UserId = t["UserId"].ToString(),
                                UserName = t["UserName"].ToString()
                            };
                        });
                        foreach (var item in dtltask)
                        {
                            item.AssignUser = username?.FirstOrDefault(o => o.UserId == item?.AssignUser)?.UserName;
                        }
                        return dtltask;
                    }

                }
                return new List<TaskLsit>();
            });
           
           
        }
        /// <summary>
        /// 判断查询审核历史按钮是否可用
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private bool FolwcommandCanExecute()
        {
            return string.IsNullOrWhiteSpace(WORKIDNumber) == false;
        }
        /// <summary>
        /// 判断按钮是否可用
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private bool ReverseCanExecute()
        {
            if (string.IsNullOrWhiteSpace(DocumentNumber)&&string.IsNullOrWhiteSpace(BillNo))//string.IsNullOrWhiteSpace(SelectText) || 
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 执行反写数据方法
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void ReverseDoExecute(object obj)
        {
            var Http_ = HelpTools.IOC.Getobject<Http>();
            Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
            Http_.Uir = "http://cpms_Project.scrbg.com/json.rpc";
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            //单据反写
            if ((obj as string) == "1")
            {
                string strconfig =   HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                await Task.Delay(2000);
                var selctsata =await Task.Run(() =>
                 {
                    return DbContext_.Where($"SELECT a.BillId, a.WorkId FROM {SelectText} a WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                     {
                         return new
                         {
                             BillId = o["BillId"].ToString(),
                             WorkId = o["WorkId"].ToString(),
                         };
                     }).FirstOrDefault();
                 });
                if (string.IsNullOrWhiteSpace(selctsata?.BillId)|| string.IsNullOrWhiteSpace(selctsata?.WorkId))
                {
                    Dialog_.OpenDialog = false;
                    Dialog_.OpenMessage("没有查询到单据数据");
                    return;
                }
                switch (SelectText.Split("_")[1])
                {
                    case "Gcjsb":
                        parameterModel.@params = new
                        {
                            Id= selctsata.BillId,
                           State=2 ,
                            workId= selctsata.WorkId,
                            trans=new {
                            TimeOut=10000
                              } ,
                           isCommit=false
                        };
                        break;
                    case "Qtjs":
                        parameterModel.@params = new
                        {
                            Id= selctsata.BillId,
                            State = 2,
                            workId= selctsata.WorkId,
                            isCommit= false
                        };
                        break;
                    default:
                        break;
                }
                parameterModel.method = $"SettleProject.{SelectText.Split("_")[1]}.AuditAfter";
                ResponseData = await Http_.PostData(parameterModel, "", "application/json");
                Dialog_.OpenDialog = false;
                return;
            }
            //传输财务
            if ((obj as string) == "2")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                await Task.Delay(2000);
                var selctsata = await Task.Run(() =>
                {
                    return DbContext_.Where($"SELECT a.BillId, a.WorkId FROM {SelectText} a WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                    {
                        return new
                        {
                            BillId = o["BillId"].ToString(),
                            WorkId = o["WorkId"].ToString(),
                        };
                    }).FirstOrDefault();
                });
                if (string.IsNullOrWhiteSpace(selctsata?.BillId) || string.IsNullOrWhiteSpace(selctsata?.WorkId))
                {
                    Dialog_.OpenDialog = false;
                    Dialog_.OpenMessage("没有查询到单据数据");
                    return;
                }
                switch (SelectText.Split("_")[1])
                {
                    case "Gcjsb":
                        parameterModel.@params = new
                        {
                            BillId = selctsata.BillId,
                            AmountCannotEmpty = true
                        };
                        break;
                    case "Qtjs":
                        parameterModel.@params = new
                        {
                            BillId = selctsata.BillId,
                            AmountCannotEmpty = true
                        };
                        break;
                    case "ReturnBaoZhengJin":
                        parameterModel.@params = new
                        {
                            BillId = selctsata.BillId,
                        };
                        parameterModel.method = "SettleProject.ReturnBaoZhengJinJS.SendToKD";
                        break;
                    default:
                        break;
                }
                if(string.IsNullOrWhiteSpace(parameterModel.method))
                parameterModel.method = $"SettleProject.{SelectText.Split("_")[1]}.SendToKD";
                ResponseData = await Http_.PostData(parameterModel, "", "application/json");
                Dialog_.OpenDialog = false;
                return;
            }
            //设置为共享审核
            if ((obj as string) == "3")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                switch (SelectText.Split("_")[1])
                {
                    case "Gcjsb":
                        if (DbContext_.Update($"UPDATE Settle_Gcjsb SET State=9 WHERE BillNo='{DocumentNumber}'") > 0)
                        {
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        break;
                    case "Qtjs":
                        if (DbContext_.Update($"UPDATE Settle_Qtjs SET State=9 WHERE BillNo='{DocumentNumber}'") > 0)
                        {
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("修改成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("修改失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        break;
                    default:
                        break;
                }
            }
            //清除缓存
            if ((obj as string) == "4")
            {
                parameterModel.@params = new
                {
                    Id = DocumentNumber
                };
                parameterModel.method = "SettleProject.WorkFlowService.Clearcache";
                Dialog_.OpenDialog = true;
                ResponseData = await Http_.PostData(parameterModel, "", "application/json");
                Dialog_.OpenDialog = false;
                return;
            }
            //工程过程查询结算合同金额
            if ((obj as string) == "5")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                var combdata = await Task.Run(() =>
                {
                    var data = DbContext_.Where($"SELECT * FROM [dbo].[Settle_Gcjsb] WHERE BillNo='{DocumentNumber}'");
                    var dataDtl = DbContext_.Where($"SELECT * FROM [dbo].[Settle_GcjsbDtl] WHERE [BillId] = '{data.Rows[0]["BillId"]}' And DataType=1 AND IsDetail = '1'").Select().Select(t =>
                    {
                        return new
                        {
                            SourceDtlId= t["SourceDtlId"]?.ToString(),
                            XmCode = t["XmCode"]?.ToString(),
                            XmName = t["XmName"]?.ToString(),
                            monthAmount = t["monthAmount"]?.ToString()
                        };
                    });
                    
                    var SettledAmountlist= DbContext_.Where($"" +
                        $"  SELECT ISNULL(SUM(a.monthAmount),0) AS LeiJiAmount, ISNULL(SUM(a.monthQty), 0) AS LeiJiQty, a.SourceDtlId as Id " +
                        $"  FROM dbo.Settle_GcjsbDtl(nolock) AS a" +
                        $"  LEFT JOIN dbo.Settle_Gcjsb AS b ON  b.BillId = a.BillId" +
                        $"  WHERE b.ContractId = '{data.Rows[0]["ContractId"]}' AND DataType = 1 AND b.State = 2 AND a.SourceDtlId IN({string.Join(",", dataDtl.Select(o=>$"'{o.SourceDtlId}'"))}) GROUP BY a.SourceDtlId").Select().Select(o =>
                    {
                        return new
                        {
                            LeiJiAmount = o["LeiJiAmount"].ToString(),
                            LeiJiQty = o["LeiJiQty"].ToString(),
                            Id = o["Id"].ToString()     
                        };
                    });
                    DbContext_.SqlConfigstr = "Data Source=192.168.100.6;Initial Catalog=SRBG_CBM;User ID=sa;Password=asdw@122";
                    var Cbmlist= DbContext_.Where($"SELECT a.DtlId,a.Amount,a.SettledAmount,a.SettledQty FROM CBM_FBContractList a WHERE a.DtlId in ({string.Join(",", dataDtl.Select(o => $"'{o.SourceDtlId}'"))}) ").Select().Select(t =>
                    {
                        return new
                        {
                            DtlId = t["DtlId"].ToString(),
                            Amount = t["Amount"].ToString(),
                            SettledAmount = t["SettledAmount"].ToString(),
                            SettledQty = t["SettledQty"].ToString()
                        };
                    });
                    List<GcjsbDtlCBM> GcjsbDtlCBMListSource = new List<GcjsbDtlCBM>();
                    foreach (var item in SettledAmountlist)
                    {
                        var dtl = Cbmlist.Single(t=>t.DtlId==item.Id);
                        var dtl1 = dataDtl.Single(t => t.SourceDtlId == item.Id);
                        string number=string.Empty;
                        try
                        {
                            number = (Decimal.Parse(dtl.Amount) - Decimal.Parse(string.IsNullOrWhiteSpace(dtl.SettledAmount)?"0": dtl.SettledAmount)).ToString();
                        }
                        catch
                        {

                        }
                        
                        GcjsbDtlCBMListSource.Add(new GcjsbDtlCBM()
                        {
                            DtlId= dtl1.SourceDtlId,
                            XmCode= dtl1.XmCode,
                            XmName= dtl1.XmName,
                            monthAmount= dtl1.monthAmount,
                            LeiJiAmount= item.LeiJiAmount,
                            ContractAmount= dtl.Amount,
                            SettledAmount=dtl.SettledAmount,
                            LeiJiQty= item.LeiJiQty,
                            SettledQty= dtl.SettledQty,
                            ResidueAmount = number
                        });;
                    }
                    return GcjsbDtlCBMListSource;
                });
                CBMDataView cBMDataView = new CBMDataView(combdata.Distinct().ToList());
                Dialog_.OpenDialog = false;
                cBMDataView.ShowDialog();
            }
            //处理流程没有审核历史
            if ((obj as string) == "6"&& string.IsNullOrWhiteSpace(SelectType) == false && string.IsNullOrWhiteSpace(SelectModular) == false && string.IsNullOrWhiteSpace(BillNo) == false)
            {
                
                if (string.IsNullOrWhiteSpace(SelectModular) || string.IsNullOrWhiteSpace(SelectType) || string.IsNullOrWhiteSpace(BillNo)) return;
                DbContext_.SqlConfigstr = $"Data Source=192.168.100.6;Initial Catalog={SelectModular};User ID=sa;Password=asdw@122";
                var data = DbContext_.Where($"SELECT * FROM [dbo].[{SelectType}] WHERE BillNo='{BillNo}'");
                // JsonModel jsonModel = new JsonModel("SettleProject.WorkFlowService.Clearcache", new { BillId = data.Rows[0]["BillId"] });
                parameterModel.method = "SettleProject.WorkFlowService.Clearcache";
                parameterModel.@params = new
                {
                    BillId = data.Rows[0]["BillId"]
                };
                await Http_.PostData(parameterModel, "", "application/json");
                if (data.Rows.Count > 1)
                {
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("处理失败不满足处理条件请手动处理", "消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                DbContext_.SqlConfigstr = "Data Source=192.168.100.150;Initial Catalog=SRBG_FlowEngin;User ID=sa;Password=sclq@pcwp1.0";//切换为流程引擎数据库
                var data1 = DbContext_.Where($"SELECT * FROM [WORK]  WHERE WORKID='{data.Rows[0]["WorkId"]}'");
                if (data1 == null || data1.Rows.Count == 0)
                {
                    DbContext_.SqlConfigstr = $"Data Source=192.168.100.6;Initial Catalog={SelectModular};User ID=sa;Password=asdw@122";
                    var data2 = DbContext_.Update($"UPDATE {SelectType} set WorkId=NULL,State =0  WHERE BillId='{data.Rows[0]["BillId"]}'");
                    if (data2 > 0)
                    {
                        WPFDevelopers.Minimal.Controls.MessageBox.Show("处理成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    WPFDevelopers.Minimal.Controls.MessageBox.Show("处理失败", "消息", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                else
                {
                    if (data1.Rows[0]["STATE"].ToString() == "2")
                    {
                        var data3 = DbContext_.Update($"update WORK set STATE = 0 where WORKID = '{data.Rows[0]["WorkId"]}'");
                        if (data3 > 0)
                        {
                            var data4 = DbContext_.Where($"SELECT A.DISPID, B.TASKTYPE, C.UNITINDEX, C.UNITNAME, A.USERNAME, B.WORKID, A.STATE,B.STATE AS TASKSTATE,A.NOTIFYTIME, A.FINISHTIME, B.TASKID, E.PRIORTASKID, A.ISPASS " +
                                $"FROM USERDISP A WITH(NOLOCK) INNER JOIN TASK B WITH(NOLOCK) ON A.TASKID = B.TASKID INNER JOIN UNIT C WITH(NOLOCK) ON B.UNITID = C.UNITID INNER JOIN WORK D WITH(NOLOCK) ON B.WORKID = D.WORKID LEFT " +
                                $"JOIN TASKORDER E ON B.TASKID = E.NEXTTASKID WHERE D.STATE <> 2 AND " +
                                $"D.WORKID = '{data.Rows[0]["WorkId"]}' ORDER BY E.PRIORTASKID");
                            if (data4.Rows.Count > 0)
                            {
                                WPFDevelopers.Minimal.Controls.MessageBox.Show("处理成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                                return;
                            }
                        }
                    }
                    else
                    {
                        var data4 = DbContext_.Where($"SELECT A.DISPID, B.TASKTYPE, C.UNITINDEX, C.UNITNAME, A.USERNAME, B.WORKID, A.STATE,B.STATE AS TASKSTATE,A.NOTIFYTIME, A.FINISHTIME, B.TASKID, E.PRIORTASKID, A.ISPASS " +
                                            $"FROM USERDISP A WITH(NOLOCK) INNER JOIN TASK B WITH(NOLOCK) ON A.TASKID = B.TASKID INNER JOIN UNIT C WITH(NOLOCK) ON B.UNITID = C.UNITID INNER JOIN WORK D WITH(NOLOCK) ON B.WORKID = D.WORKID LEFT " +
                                            $"JOIN TASKORDER E ON B.TASKID = E.NEXTTASKID WHERE D.STATE <> 2 AND " +
                                            $"D.WORKID = '{data.Rows[0]["WorkId"]}' ORDER BY E.PRIORTASKID");
                        if (data4.Rows.Count > 0)
                        {
                            WPFDevelopers.Minimal.Controls.MessageBox.Show("处理成功", "消息", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }

                }
                return;
            }
            //工程过程查询超施工日志
            if ((obj as string) == "7")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                var combdata = await Task.Run(() =>
                {
                    var data = DbContext_.Where($"SELECT * FROM [dbo].[Settle_Gcjsb] WHERE BillNo='{DocumentNumber}'");
                    var dataDtl = DbContext_.Where($"SELECT * FROM [dbo].[Settle_GcjsbDtl] WHERE [BillId] = '{data.Rows[0]["BillId"]}' And DataType=1 AND IsDetail = '1' AND monthQty != 0").Select().Select(t =>
                    {
                        return new
                        {
                            SourceDtlId = t["SourceDtlId"]?.ToString(),
                            XmCode = t["XmCode"]?.ToString(),
                            XmName = t["XmName"]?.ToString(),
                            FbfxName = t["FbfxName"]?.ToString(),
                            CheckNum = t["CheckNum"]?.ToString()

                        };
                    });

                    var SettledAmountlist = DbContext_.Where($"SELECT b.* FROM [dbo].[Project_WorkLogDtl] b JOIN [dbo].[Project_WorkLog] a  ON b.WorkLogId=a.WorkLogId WHERE a.FBContractId='{data.Rows[0]["ContractId"]}' AND b.FBListId In({string.Join(",", dataDtl.Select(o => $"'{o.SourceDtlId}'"))})").Select().Select(o =>
                        {
                            return new
                            {
                                WorkLogDtlId = o["WorkLogDtlId"].ToString(),
                                FBListId= o["FBListId"].ToString(),
                                Qty = Decimal.Parse(string.IsNullOrWhiteSpace(o["Qty"]?.ToString())?"0": o["Qty"]?.ToString()),
                                SettledQty = Decimal.Parse(string.IsNullOrWhiteSpace(o["SettledQty"].ToString()) ?"0": o["SettledQty"].ToString()) 
                            };
                        });

                    var LJSettledAmount = DbContext_.Where($"" +
                                                             $"  SELECT ISNULL(SUM(a.monthAmount),0) AS LeiJiAmount, ISNULL(SUM(a.monthQty), 0) AS LeiJiQty, a.SourceDtlId as Id " +
                                                              $"  FROM dbo.Settle_GcjsbDtl(nolock) AS a" +
                                                              $"  LEFT JOIN dbo.Settle_Gcjsb AS b ON  b.BillId = a.BillId" +
                       $"  WHERE b.ContractId = '{data.Rows[0]["ContractId"]}' AND DataType = 1 AND b.State = 2 AND a.SourceDtlId IN({string.Join(",", dataDtl.Select(o => $"'{o.SourceDtlId}'"))}) GROUP BY a.SourceDtlId").Select().Select(o =>
    {
        return new
        {
            LeiJiAmount = o["LeiJiAmount"].ToString(),
            LeiJiQty = o["LeiJiQty"].ToString(),
            Id = o["Id"].ToString()
        };
    });

                    List<WorkLogDtl> GcjsbDtlCBMListSource = new List<WorkLogDtl>();
                    foreach (var item in dataDtl)
                    {
                        var dtl1 = LJSettledAmount.FirstOrDefault(t => t.Id == item.SourceDtlId);//累积结算数据
                        var work = SettledAmountlist.Where(t => t.FBListId == item.SourceDtlId);//施工日志
                        var workdtl = work.Where(t => t.FBListId == item.SourceDtlId&&t.SettledQty!=0);
                        string number = string.Empty;
                        try
                        {
                            number = (work.Sum(o => o.Qty) - work.Sum(o => o.SettledQty)).ToString();
                        }
                        catch
                        {

                        }
                        GcjsbDtlCBMListSource.Add(new WorkLogDtl()
                        {
                            WorkLogDtlId = workdtl.Count()==1? workdtl?.FirstOrDefault()?.WorkLogDtlId:string.Join(",",workdtl.Select(u=>u.WorkLogDtlId)),
                            XmCode = item.XmCode,
                            XmName = item.XmName,
                            FbfxName = item.FbfxName,
                            CheckNum = item.CheckNum,
                            LJCheckNum = dtl1?.LeiJiQty,
                            Qty = work.Sum(o=>o.Qty),
                            SettledQty = work.Sum(o => o.SettledQty),
                            ResidueAmount = number
                        }); ;
                    }
                    return GcjsbDtlCBMListSource;
                });
                WorklogDataView cBMDataView = new WorklogDataView(combdata.Distinct().ToList());
                Dialog_.OpenDialog = false;
                cBMDataView.ShowDialog();
            }
            //处理工程过程负结算 清单有多了1块或清单少1块
            if ((obj as string) == "8")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                ResponseData= await Task.Run(() =>
                {
                    try
                    {
                        var data = DbContext_.Where($"SELECT * FROM [dbo].[Settle_Gcjsb] WHERE BillNo='{DocumentNumber}'");
                        var dataDtl = DbContext_.Where($"SELECT * FROM [dbo].[Settle_GcjsbDtl] WHERE [BillId] = '{data.Rows[0]["BillId"]}' And DataType=1 AND IsDetail = '1' AND sumAmount !=0").Select().Select(t =>
                        {
                            return new
                            {
                                SqSumAmount = Convert.ToDecimal(t["SqSumAmount"]),
                                monthAmount = Convert.ToDecimal(t["monthAmount"]),
                                sumAmount = Convert.ToDecimal(t["sumAmount"]),
                                DtlId = t["DtlId"]?.ToString(),

                            };
                        });
                        foreach (var item in dataDtl)
                        {
                            if (string.IsNullOrWhiteSpace(item.DtlId)) continue;
                            DbContext_.Update($"UPDATE Settle_GcjsbDtl SET monthAmount=monthAmount-sumAmount,sumAmount=0 WHERE DtlId='{item.DtlId}'");
                        }
                        return "成功";
                    }
                    catch(Exception ex)
                    {
                        return ex.Message;
                    }
                    

                });            
                Dialog_.OpenDialog = false;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        private async void AddModularListCommandMethodDoExecute(object obj)
        {
            if (TypeList_ != null && TypeList_.Count > 0)
                TypeList_.Clear();
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            DbContext_.SqlConfigstr = "Server=192.168.100.84;Database=PCWP_OperationHelper;uid=sa;pwd=asdw@123";
          var Listdata=   await Task.Run(() =>
            {
                return DbContext_.Where($"SELECT  a.DatabaseNameValue,a.DataSheet,a.DataSheetValue FROM DataBasekey a WHERE DatabaseNameValue='{SelectModular}'").Select().Select(o =>
                {
                    return new
                    {
                        DatabaseNameValue = o["DatabaseNameValue"].ToString(),
                        DataSheetValue = o["DataSheetValue"].ToString(),
                        DataSheet= o["DataSheet"].ToString()
                    };
                });
            });
            foreach (var item in Listdata)
            {
                if (item.DataSheet != null && item.DataSheetValue != null)
                {

                    if (!TypeList_.ContainsKey(item.DataSheetValue))
                        TypeList_?.Add(item.DataSheetValue, item.DataSheet);
                }
            }

        }
        private bool AddModularListCommandMethodCanExecute()
        {
            return true;
        }
        #endregion
        #region 命令
        public Command Selectcommand { get; set; }
        //
        public Command AddModularListCommand { get; set; }
        /// <summary>
        /// 查询审核历史
        /// </summary>
        public Command Folwcommand { get; set; }
        /// <summary>
        /// 查询审核历史 选择模块
        /// </summary>
        public Command FolwModularListCommand { get; set; }
        
        #endregion
        #region 属性
        private string Title_ = "工程";

        public string Title
        {
            get { return Title_ ; }
            set { Title_ = value; }
        }

        private Dictionary<string,string> DocumentType_;
        /// <summary>
        /// 单据类型选择
        /// </summary>
        public Dictionary<string,string> DocumentType
        {
            get {
                if (DocumentType_ == null|| DocumentType_.Count==0)
                {
                    DocumentType_ = new Dictionary<string, string>();
                   var IConfigurationHelp_=   HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>();
                    foreach (var item in IConfigurationHelp_.GetSetUpTableModel().Where(t=>t.ModuleName== Title_))
                    {
                        DocumentType_.Add(item.TableValue, item.TableName);
                    }
                    return DocumentType_;
                }
                else
                {
                    return DocumentType_;
                }
                }
            set { DocumentType_ = value; }
        }


        private string DocumentNumber_;
        /// <summary>
        /// 单据数据
        /// </summary>
        public string DocumentNumber
        {
            get { return DocumentNumber_; }
            set { DocumentNumber_ = value;
                SetProperty(ref DocumentNumber_, DocumentNumber);
            }
        }

        private string SelectText_;
        /// <summary>
        /// 选中的类型数据
        /// </summary>
        public string SelectText
        {
            get { return SelectText_; }
            set { SelectText_ = value; }
        }
        private string ResponseData_;

        public string ResponseData
        {
            get { return ResponseData_; }
            set {
                ResponseData_ = value;
                SetProperty(ref ResponseData_, ResponseData);
            }
        }


        private Dictionary<string, string> ModularList_;
        /// <summary>
        /// 模块
        /// </summary>
        public Dictionary<string, string> ModularList
        {
            get
            {
                if (ModularList_ == null)
                {
                    ModularList_ = new Dictionary<string, string>();
                    ModularList_.Add("SRBG_Project", "工程");
                    ModularList_.Add("SRBG_Equip", "设备");
                    ModularList_.Add("SRBG_Revolve", "周财");
                    ModularList_.Add("SRBG_Tender", "招标");
                    ModularList_.Add("SRBG_Material", "物资");
                    ModularList_.Add("SRBG_CBM", "合同");
                }
                return ModularList_;
            }
            set
            {
                ModularList_ = value;
                SetProperty(ref ModularList_, ModularList);
            }
        }

        private ObservableDictionary<string, string> TypeList_;
        /// <summary>
        /// 模块类型
        /// </summary>
        public ObservableDictionary<string, string> TypeList
        {
            get
            {
                if (TypeList_ == null)
                {
                    TypeList_ = new ObservableDictionary<string, string>();


                }
                return TypeList_;
            }
            set
            {
                TypeList_ = value;
                SetProperty(ref TypeList_, TypeList);
            }
        }

        private string SelectModular_;
        /// <summary>
        /// 选择的模块
        /// </summary>
        public string SelectModular
        {
            get
            {     
                return SelectModular_;
            }
            set { SelectModular_ = value; }
        }
        private string SelectType_;
        /// <summary>
        /// 选择模块类型
        /// </summary>
        public string SelectType
        {
            get { return SelectType_; }
            set { SelectType_ = value; }
        }
        private string BillNo_;
        /// <summary>
        /// 单据编号
        /// </summary>
        public string BillNo
        {
            get { return BillNo_; }
            set { BillNo_ = value; }
        }
        private string WORKIDNumber_;
        /// <summary>
        /// 查询审核流程单据编号
        /// </summary>
        public string WORKIDNumber
        {
            get { return WORKIDNumber_; }
            set { WORKIDNumber_ = value; }
        }
        private List<TaskLsit> TaskList_;
        /// <summary>
        /// 审核历史
        /// </summary>
        public List<TaskLsit> TaskList
        {
            get { return TaskList_; }
            set { TaskList_ = value;
                SetProperty(ref TaskList_, TaskList);
            }
        }

        #endregion
    }
}
